package com.wjk.cms.controller;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.wjk.cms.common.Result;
import com.taobao.api.ApiException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@RestController
@RequestMapping("dingding")
public class DingdingController extends UnauthenticatedController {

    @PostMapping("/send")
    public Result send(
            @RequestParam("access_token") String access_token,
            @RequestParam("content") String content,
            @RequestParam("atMobiles") String atMobiles,
            @RequestParam("isAtAll") String isAtAll
    ) throws ApiException {
        String serverUrl = "https://oapi.dingtalk.com/robot/send?access_token=" + access_token;
        DingTalkClient client = new DefaultDingTalkClient(serverUrl);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        request.setText(text);
        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();

        if ("1".equals(isAtAll)) {
            at.setIsAtAll("true");
        } else {
            String[] list = atMobiles.split(",");
            at.setAtMobiles(Arrays.asList(list));
            at.setIsAtAll("false");
        }
        request.setAt(at);
        OapiRobotSendResponse response = client.execute(request);
        return Result.ok();
    }

}
